package com.cskaoyan.common;

import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.utils.JacksonUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author Pudding
 * @Date 2024/5/23 10:15
 */
public class CommonServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        int index = uri.indexOf("/fetch");
        String methodName;
        if (index != -1) {
            methodName = "fetch";
        }else {
            methodName = uri.substring(uri.lastIndexOf("/") + 1);
        }

        try {
            // 方法名后面要继续增加参数：方法的参数类型和顺序
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            Object result = method.invoke(this, req, resp); //传过去请求报文和响应报文

            //返回这种类型对象就不需要我们手动再去写响应报文了
            if (result instanceof BaseRespVo) {
                String jsonStr = JacksonUtil.write(result);
                resp.setContentType("application/json;charset=UTF-8");
                resp.getWriter().println(jsonStr);
            }
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
